package se.com.movie.reader.writer;

import java.util.LinkedList;
import java.util.Queue;

import se.com.movie.reader.model.Movie;

public class MovieWriter extends Thread {
	private Queue<Movie> mMessage = new LinkedList<Movie>();
	private static MovieWriter mMovieWriter = null;
	private boolean mQuitWhenDone = false;
	private boolean mRunning = true;

	public static MovieWriter getInstance() {
		if (mMovieWriter == null) {
			mMovieWriter = new MovieWriter();
			mMovieWriter.start();
		}
		return mMovieWriter;
	}

	private MovieWriter() {
	}

	public synchronized void write(Movie movie) {
		mMessage.add(movie);
		notify();
	}

	private synchronized Movie read() throws InterruptedException {
		if (mMessage.isEmpty()) {
			if (!mQuitWhenDone) {
				wait();
			} else {
				mRunning = false;
			}
		}
		return mMessage.poll();
	}

	@Override
	public void run() {
		try {
			XMLWriter.open();
			Movie movie = null;
			while (mRunning) {
				movie = read();
				if (movie != null) {
					XMLWriter.write(movie);
				}
			}
			System.out.println("Messag Writer is Closed");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			XMLWriter.close();
		}
	}

	public void setQuitWhenDone(boolean quitWhenDone) {
		if (isAlive()) {
			synchronized (this) {
				notify();
			}
			mRunning = false;
		}
		mQuitWhenDone = quitWhenDone;
	}
}
